package com.milorad.ads.pages.admin;

import java.util.List;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.milorad.ads.data.dao.interfaces.AdvertDao;
import com.milorad.ads.data.domain.Advert;
import com.milorad.ads.data.domain.Advert.AdvertStatus;
import com.milorad.ads.pages.BasePage;

public class AdvertsApprovalPage extends BasePage {
	
	@SpringBean
	private AdvertDao advertDao;
	
	public AdvertsApprovalPage() {				
		
		Advert advert = new Advert();
		advert.setStatus(AdvertStatus.PENDING);
		List<Advert> pendingAdverts = advertDao.find(advert);
				
		add(new Label("adsListTitle", getAdsListTitle(pendingAdverts)));
       	
       	add(createPendingAdvertsList(pendingAdverts));
       	
       	add (new BookmarkablePageLink<Void>("adminPanelLink", MainAdminPage.class));
	}

	private String getAdsListTitle(List<Advert> pendingAdverts) {
		
		if (pendingAdverts.isEmpty()) {
			return "Currently there are no pending adverts.";
		} else if (pendingAdverts.size() > 1) {
			return "There are " + pendingAdverts.size() + " small adverts waiting approval.";
		} else {
			return "There is 1 small advert waiting approval.";
		}
	}

	private ListView<Advert> createPendingAdvertsList(List<Advert> pendingAdverts) {
		return new ListView<Advert>("adsList", pendingAdverts) {
			
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(ListItem<Advert> item) {
				Advert advert = item.getModelObject();
				item.add(new Label("adTitle", advert.getTitle()+"("+advert.getCategory().getName()+")"));
				item.add(new Label("adText", advert.getText()));		
				
				item.add(new Link<Advert>("approveButton", item.getModel()) {						
						private static final long serialVersionUID = 2221207599260261693L;
						
						@Override
						public void onClick() {
							approveAdvert(getModelObject());							
						}					
				});
				
				item.add(new Link<Advert>("rejectButton", item.getModel()) {					
					private static final long serialVersionUID = 2221207599260261693L;
					
					@Override
					public void onClick() {
						rejectAdvert(getModelObject());							
					}					
				});
			}			
		};
	}

	private void approveAdvert(Advert advert) {

		advert.setStatus(AdvertStatus.APPROVED);
		advertDao.save(advert);
		setResponsePage(AdvertsApprovalPage.class);
	}

	private void rejectAdvert(Advert advert) {
	
		advert.setStatus(AdvertStatus.REJECTED);
		advertDao.save(advert);
		setResponsePage(AdvertsApprovalPage.class);
	}
}